<?php
class PResumesDownloader
{
   public static function setResumeHead($resume, $content, $source='51job') {
      // first check if the resume is under system=1 job position. If so, we don't need to add any resume head section 
      if($resume->jobsystem) {
         return $content; 
      }

      $joblocation = $resume->province ?  (($resume->city && $resume->province != $resume->city) ? 
                                            $resume->province.'-'.$resume->city : $resume->province) : ''; 
      if($joblocation) $joblocation = '（' . $joblocation .  '）'; 

      // we create a common for all sources with necessary information. 
      $resumehead = '<div id="resumehead">
                     <table width="768" cellspacing="0" cellpadding="0" border="0" align="center" style="margin:0 auto;border:0;font-size:13px;">
                     <tr><td style="width:85%">
                        <table cellspacing="0" cellpadding="0" border="0">
                         <tr><td width="75px" valign="top" align="left"><span style="height:10px;"><strong>应聘职位：</strong></span></td>
                           <td valign="top" align="left" class="blue1">' . $resume->jobtitle . $joblocation . '</td>
                         </tr>
                         <tr><td width="75px" valign="top" align="left"><span style="height:10px;"><strong>投递时间：</strong></span></td>
                           <td valign="top" align="left" class="blue1">'.JHtml::_('date', $resume->date_added, 'Y-m-d').'</td>
                         </tr>
                        <tr><td width="75px" valign="top" align="left"><span style="height:10px;"><strong>简历匹配度：</strong></span></td>
                           <td><table cellspacing="0" cellpadding="0" border="0">
                               <tr><td><div class="barp"><table cellspacing="0" cellpadding="0" border="0" class="baro" style="width:'.$resume->match_degree.'%"><tr><td></td></tr>
                                  </table></div></td><td><font color="#0D7D00"><b>'.$resume->match_degree.'%</b></font></td></tr></table>
                           </td>
                        </tr>
                        </table>
                     </td>'; 

      // add each logo if it's present in original html 
      switch($source) {
         case '51job': 
            $resumehead .= '
                     <td><table><tr><td valign="top" align="right" style="padding-right:0px;" class="blue1">
                         <img src="http://img01.51jobcdn.com/im/2009/resumetemplate/logo.gif" alt="前程无忧"></td></tr></table>
                     </td>'; 
         break; 

      case 'zhilian': 
            $resumehead .= '
                     <td><table><tr><td valign="top" align="right" style="padding-right:0px;" class="blue1">
                         <img width="133" height="71" align="right" class="headerlogo" src="http://img02.zhaopin.cn/2012/img/rd/logo.png" alt=""></td></tr></table>
                     </td>'; 

         break; 

         case 'jiancai': 
            $resumehead .= '
                     <td><table><tr><td valign="top" align="right" style="padding-right:0px;" class="blue1">
                         <img width="133" height="71" align="right" class="headerlogo" src="http://my.800hr.com/img/email_logo/logo_11.gif" alt=""></td></tr></table>
                     </td>'; 
         break; 

      }

      $resumehead = '<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head><body>'.$resumehead.'</tr></table></div></body></html>'; 

      // we cannot use regexp method to replace as <body> is too complicated with many kinds of format 
      $htmldoc = new DomDocument(); 
      @$htmldoc->loadHTML($content); 
      $bodies = $htmldoc->getElementsByTagName('body'); 
      if(empty($bodies)) {
         return $content; 
      }

      $body = $bodies->item(0);

      $htmldiv = new DomDocument(); 
      @$htmldiv->loadHTML($resumehead);

      $inode = $htmldiv->getElementById("resumehead"); 
      $inode = $htmldoc->importNode($inode, true); 
      $body->insertBefore($inode, $body->firstChild);

      return $htmldoc->saveHTML(); 
   }

   // common resume download functions 
   public static function generatePDF($spath, $source, $dpath) {
      static $phantomjs_exec, $phantomjs_rasterize;
      if(!$phantomjs_exec || !$phantomjs_rasterize) {
         $phantomjs_path = realpath(JPATH_ROOT."/../tools/userbrowser/phantomjs");
         $phantomjs_exec = $phantomjs_path . (PHP_INT_SIZE==8 ? "/bin/phantomjs" : "/bin/phantomjs_ia32");
         $phantomjs_rasterize = $phantomjs_path . "/examples/rasterize.js";
      }

      switch($source) {
         case '51job':
         default: 
            $tag = "前程无忧"; 
         break; 
         case 'zhilian': 
            $tag = "智联招聘"; 
         break; 
         case 'lagou': 
            $tag = "拉勾网"; 
         break; 
         case 'jiancai': 
            $tag = "建筑英才"; 
         break; 
      }


      $pdffile = $dpath."/".str_replace('|', '/', basename($spath)."($tag).pdf");
      $urls = explode("/", $spath);
      $nurls = array();
      foreach($urls as $url) {
         array_push($nurls, encodeURIComponent($url));
      }

      $url = 'http://' . PUtil::serverDomain() . "/" . implode("/", $nurls) . "/" . $source . "/resume.html";

      $config = JFactory::getConfig();
      $proxyoption = '';
      if($config->get("proxysites") && in_array($source, $config->get("proxysites"))) {
         $proxyport = $config->proxy[array_rand($config->proxy)];

         // add --port as part of 
         $proxyoption = "--proxy=" . $proxyport;
      }

      $command = "$phantomjs_exec $proxyoption $phantomjs_rasterize " . $url . " " . escapeshellarg($pdffile) . " 7.5in*11in 1.0";

      // we use proc_open with pipes to fetch error output
      try {
         execTimeout($command, 60);
         return $pdffile;
      }
      catch(Exception $e) {
         echoDbg("Could not run command $command:\n$e");
         return false;
      }

   }

   public static function mergePDF($pdffiles=array(), $output) {
      if(empty($pdffiles) || empty($output))
         return false;

      if(count($pdffiles) <= 1) {
         $command = "/bin/cp -f " . escapeshellarg(implode(" ", $pdffiles)) . ' ';
      } else {
         $files = '';
         foreach($pdffiles as $pdf) {
            $files .= escapeshellarg($pdf) . ' ';
         }

         $command = "/usr/bin/pdfunite " . $files;
      }

      $command .= escapeshellarg($output);

      try {
         execTimeout($command, 60);
         return true;
      }
      catch(Exception $e) {
         echoDbg("Could not run command $command:\n$e");
         return false;
      }

   }

   public static function copyFiles($resume, $resumefile, $savedir) {
      // resumefile could be empty or not based on caller. 
      // its directory might be in various structure either in old path or new storage path when this function was written 
      $sourcefolders = array();
      
      if(!$resumefile)
         $resumefile = $resume->resumefile; 

      if(is_array($resumefile)) {
         foreach($resumefile as $file) {
            $m = self::copyFiles($resume, $file, $savedir);            
            $sourcefolders = array_unique(array_merge($sourcefolders, $m)); 
         }

         return $sourcefolders; 
      }

      // when we reach here, resumefile must be valid 
      if(!$resumefile && !is_file($resumefile))
         return $sourcefolders; 

      // resumefile could be: 
      // cloudpath+"/resumes/aa/bb/cc/dd/aabbccdd/version/source/resume.html
      // cloudpath+"/company/<companydi>/resumes/resumeid/source/resume.html 
      // cloudpath+"/company/123/111/100/<companyid>/resumes/<resumeid>/source/resume.html 

      $folder = dirname($resumefile); 

      $source = basename(dirname($resumefile)); 
      array_push($sourcefolders, $source); 
      
      $content = file_get_contents($resumefile);
      $content = preg_replace("/display:__ppp_display_none__/", "", $content);
      # below two to make pdf looks in better shape 
      $content = preg_replace("/font-weight:\s*(700|bold)\s*(;)?/i", "", $content);

      // when our process server is slow, the resume.html may not be in utf-8 chars 
      $charset = detectCharsetEncoding(null, $resumefile);
      if($charset != false && $charset != 'UTF-8') {
         try {
            $content = mb_convert_encoding($content , 'UTF-8' ,  $charset);
         }
         catch(Exception $e) { }
      }
      // the content is utf-8 now, for safety, pre-append some head to force charset in utf-8 
      $content = '<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head></html>' . $content;

      // add resume head per company 
      $content = self::setResumeHead($resume, $content, $source);
      mkdir_recursive($savedir . "/" . $source);
      file_put_contents($savedir."/".$source."/resume.html", $content);

      return $sourcefolders;
   }
}

